package com.dcivision.dms.web;

import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsDocumentDetail;
import com.dcivision.dms.bean.DmsValidation;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.DocumentValidateManager;
import com.dcivision.dms.core.EmptyContentException;
import com.dcivision.dms.dao.DmsDocumentDetailDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;

/**
MaintDmsDocumentForm.java

This class is the for web form purpose.

@author          jerry zhou
@company         DCIVision Limited
@creation date   25/07/2005
@version         $Revision: 1.14.2.1 $
*/

public class MaintDmsRenameAction extends AbstractMaintAction{
	
  public static final String REVISION = "$Revision: 1.14.2.1 $";
  
  protected static String MESSAGE_RECORD_RENAME = "dms.message.records_rename";
  
  public String getFunctionCode() {
    return null;
  }
  
  public String getMajorDAOClassName() {
    return null;
  }
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
	MaintDmsRenameForm actionForm = (MaintDmsRenameForm) form;
	//DmsDocument document = (DmsDocument) actionForm.getFormData();
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    
	DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    
    String opMode = actionForm.getOpMode();
    /*
     * joan.xiong update code for bug EIP-153 by 2006/09/19
     */
//  DmsDocument document = docRetrievalManager.getDocumentByID(TextUtility.parseIntegerObj(actionForm.getID()));
    DmsDocument document = (DmsDocument)new com.dcivision.dms.dao.DmsDocumentDAObject(sessionContainer,conn).getDocumentByID(TextUtility.parseIntegerObj(actionForm.getID()), actionForm.getRecordStatus());
    /*
     * joan.xiong update code end
     */
    String path = docRetrievalManager.getLocationPath(TextUtility.parseIntegerObj(actionForm.getParentID()));    
    request.setAttribute("location", path);
    
    //Add By Jim Zhou       2007/0110       EIP-1292
    if (!"E".equals(document.getRecordStatus())) {
        MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
        //Integer documentID = TextUtility.parseIntegerObj(documentForm.getID());
        //DmsDocument document = docRetrievalManager.getDocument(documentID);
        DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
        StringBuffer message = new StringBuffer();
    
          
        DmsValidation validation = docValidateManager.validateOperateAction(document, false, "N");
        List lstIdMisRight = validation.getLstIdReject();
        List lstIdBeLocked = validation.getLstIdlocked();
        List lstIdBeDeleted = validation.getLstIdDeleted();
        List lstIdBeArchived = validation.getLstIdArchived();
        List lstIdRelationship = validation.getLstIdHaveRelationship();
        if (!lstIdMisRight.isEmpty() ||
            !lstIdBeLocked.isEmpty() ||
            !lstIdBeDeleted.isEmpty() ||
            !lstIdBeArchived.isEmpty()){
          for (int i=0; i<lstIdMisRight.size(); i++) {
            //request.getSession().setAttribute(org.apache.struts.Globals.ERROR_KEY,MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i))));
            //addMessage(request,MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i))));
            message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i))) + "\n");
          }
          for (int i=0; i<lstIdBeLocked.size(); i++) {
            //request.getSession().setAttribute(org.apache.struts.Globals.ERROR_KEY,MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i))));
            //addMessage(request,MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i))));
            message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i))) + "\n");
          }
          for (int i=0; i<lstIdBeDeleted.size(); i++) {
            //request.getSession().setAttribute(org.apache.struts.Globals.ERROR_KEY,MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i))));
            //addMessage(request,MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i))));
            message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i))) + "\n");
          }
          for (int i=0; i<lstIdBeArchived.size(); i++) {
            //request.getSession().setAttribute(org.apache.struts.Globals.ERROR_KEY,MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i))));
            //addMessage(request,MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i))));
            message.append(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(),"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i))) + "\n");
          }
          actionForm.setRefreshTag("1");
          addMessage(request, message.toString());
          actionForm.setDocumentName("");
          request.getSession().setAttribute(org.apache.struts.Globals.ERROR_KEY,message.toString());
          return mapping.findForward(GlobalConstant.NAV_MODE_EDIT); 
        }
    }
    //Add End
    
    try {
      if (DmsOperationConstant.RENAME_OPERATION.equals(opMode)) {
        // Insert operation.
        log.debug("enter rename");
        
        if(!actionForm.getDocumentName().equals(document.getDocumentName())){        
          this.renameRecord(mapping, actionForm, request, response);
          this.commit(request);
          actionForm.setRefreshTag("1");
          addMessage(request, MESSAGE_RECORD_RENAME);
          actionForm.setDocumentName("");
//          request.getSession().setAttribute(MESSAGE_RECORD_RENAME,MESSAGE_RECORD_RENAME);//joan.xiong add code for bug EIP-172 by 2006/10/12
          request.getSession().setAttribute(org.apache.struts.Globals.MESSAGE_KEY,MESSAGE_RECORD_RENAME);
        }
      }
    }catch (ApplicationException appEx){
      this.rollback(request);
      handleApplicationException(request, appEx);
//      throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR);
    }
    return mapping.findForward(GlobalConstant.NAV_MODE_EDIT); 
  }
  
  public void renameRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);
    DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    
    MaintDmsRenameForm documentForm = (MaintDmsRenameForm) form;
	    
    //set the docDetailList and userDefinedFieldID
    DmsDocumentDetailDAObject dmsDocumentDetailDAObj = new DmsDocumentDetailDAObject(sessionContainer,conn);
    Integer documentID = TextUtility.parseIntegerObj(documentForm.getID());
    /*
     * joan.xiong update code for bug EIP-153 by 2006/09/19
     */
//  DmsDocument document = documentRetrievalManager.getDocumentByID(documentID);
    DmsDocument document = (DmsDocument)new com.dcivision.dms.dao.DmsDocumentDAObject(sessionContainer,conn).getDocumentByID(documentID, documentForm.getRecordStatus());
    /*
     * joan.xiong update code end
     */
    //Add By Jim.Zhou
    //Add End
    /*
     * Update Code Start
     * Author	Jim.Zhou
     * Date		2006/03/29	
     */
    /*
    if ("My Favorite".equals(document.getDocumentName())){
    	throw new ApplicationException(DmsErrorConstant.DMS_MESSAGE_UNABLE_RENAME_MYFAVORIT,null);
    } else {
    	document.setDocumentName(documentForm.getDocumentName());
    }
     */
    //Add By Jim.Zhou		2006/07/14		Bug #5006
    //Add End
    /*
     * Update Code End
     */

  	document.setDocumentName(documentForm.getDocumentName());
	    
    List docDetailList =dmsDocumentDetailDAObj.getListByDocumentID(documentID);
    if(!Utility.isEmpty(docDetailList)){
      DmsDocumentDetail tmpDmsDocumentDetail =(DmsDocumentDetail)docDetailList.get(0);
      Integer userDefinedFieldID = tmpDmsDocumentDetail.getUserDefinedFieldID();
      document.setDocumentDetails(docDetailList);
      document.setUserDefinedFieldID(userDefinedFieldID);
    }

    if (Utility.isEmpty(documentForm.getDocumentName()) || "".equals(documentForm.getDocumentName().trim())){
      if (DmsDocument.FOLDER_TYPE.equals(documentForm.getDocumentType())) {
        throw new EmptyContentException(DmsErrorConstant.EMPTY_FOLDER_NAME);
      }else{
        throw new EmptyContentException(DmsErrorConstant.EMPTY_DOCUMENT_NAME);
      }
    }
    DmsDocument newDocument  = docOperationManager.renameRecord(document);
    documentForm.setFormData(newDocument);

    sessionContainer = null;
    conn = null;
    docOperationManager.release();

  }

}
